<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="searchFrom.filmId"
                   filterable
                   remote
                   clearable
                   style="width:240px;"
                   placeholder="请输入电影名称">
          <el-option
              v-for="item in tableData"
              :label="item.filmName"
              :value="item.filmId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="select">搜索</el-button>
      </el-form-item>
      <el-button type="primary" style="margin-right: 20px;float: right" @click="goBack">返回</el-button>
    </el-form>
  </el-card>

  <el-card style="margin:20px;">
    <div style="margin:10px 0 40px 10px;">
      专题详细列表
      <el-button type="success" style="float: right;margin-top:-3px;" @click="addFilm">增加影片</el-button>
    </div>
    <el-table :data="paginatedData"
              style="height: 465px">>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column prop="subjectName" label="专题名称" align="center"/>
      <el-table-column prop="filmName" label="电影名称" align="center"/>
      <el-table-column prop="releaseYear" label="上映年份" align="center"/>
      <el-table-column prop="tag" label="电影标签" align="center"
                       :formatter="tagFormatter"/>
      <el-table-column prop="createTime" label="设置时间" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="danger"
                     @click="deleteFilmSubject(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />

  </el-card>
  <el-dialog title="添加影片"
             v-model="addFilmVisible"
             style="width:1000px;height: 500px;padding:40px;">

    <el-row :gutter="10">
      <el-col :span="12">
        <el-form label-width="120px" :inline="true">
          <el-form-item label="请选择电影" style="width: 100%;">
            <el-select v-model="searchFilm.id"
                       filterable
                       remote
                       clearable
                       placeholder="请输入要选择的电影">
              <el-option
                  v-for="item in filmSearchData"
                  :key="item.value"
                  :label="item.filmName"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="filmSearch">搜索</el-button>
        <el-button @click="resetFilmSearch">重置</el-button>
        <el-button type="danger" @click="handleClose"
                   style="float: right">取消
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="14">
        <el-table
            :data="filmSearchData"
            style="width: 500px;margin-top: 10px;height: 300px;">
          <el-table-column prop="filmName" label="电影名称"/>
          <el-table-column prop="tag" label="电影类型" align="center"
                           :formatter="tagFormatter"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link
                         @click="toggleSelection(scope.row)">
                <span v-if="isSelected(scope.row.id)"><el-icon size="22px" color="red"><RemoveFilled/></el-icon></span>
                <span v-else><el-icon size="22px"><CirclePlusFilled/></el-icon></span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8">
        <p>添加的电影：</p>
        <el-scrollbar height="280px">
          <ul>
            <li v-for="(item, index) in selectedFilmsValue" :key="index">
              {{ item.filmName }}
            </li>
          </ul>
        </el-scrollbar>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" style="margin: 300px 0 0 10px"
                   @click="saveFilm">添加
        </el-button>
      </el-col>
    </el-row>


  </el-dialog>
</template>

<script setup>
import router from "@/router";
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

const goBack = () => {
  router.push('/subject')
}
const tagList = ref([]);
const regionList = ref([]);
onMounted(() => {
  loadDictOptions(tagList, 'tag');
});
const tagFormatter = (row, column, cellValue, index) => {
  if (!tagList.value || !cellValue) {
    return cellValue;
  }

  // 将斜杠分隔的字符串转换为数组
  const tagsArray = cellValue.split('/');

  // 查找并替换每个标签值
  const formattedTags = tagsArray.map(tagValue => {
    for (let item of tagList.value) {
      if (item.value === tagValue) {
        return item.label; // 返回对应的汉字内容
      }
    }
    return tagValue; // 如果没有找到对应的汉字内容，则保留原始值
  });

  // 将格式化后的标签数组重新组合为字符串
  return formattedTags.join(' / ');
};

const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchFrom = ref({
  filmId: ''
})
let subjectId = new URLSearchParams(window.location.search).get('id');
const select = () => {
  searchFrom.value.subjectId = subjectId;
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/filmSubject/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  select();
})
const resetSearch = () => {
  searchFrom.value.filmId = ''
  select();
}
const addFilmVisible = ref(false);

const addFilm = () => {
  addFilmVisible.value = true;
  filmSearch();
}
const allFilm = ref([]);
const selectAllFilm = () => {
  axios.get(BASE_URL + '/v1/film/select')
      .then((response) => {
        if (response.data.code === 2000) {
          allFilm.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  selectAllFilm();
})
const searchFilm = ref({
  id: '',
  subjectId: subjectId,
})
const filmSearchData = ref({});
const filmSearch = () => {
  let data = qs.stringify(searchFilm.value);
  axios.get(BASE_URL + '/v1/film/select/subject?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          filmSearchData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
          })
        }
      })
}
onMounted(() => {
  filmSearch();
})
const resetFilmSearch = () => {
  searchFilm.value.id = '';
  filmSearch();
};


const selectedFilmsValue = ref([]); // 已有的定义

const isSelected = (id) => {
  return selectedFilmsValue.value.some(film => film.id === id);
};

const toggleSelection = (row) => {
  const index = selectedFilmsValue.value.findIndex(film => film.id === row.id);

  if (index > -1) { // 如果找到，则表示该行已被选择，执行删除操作
    selectedFilmsValue.value.splice(index, 1);
  } else { // 否则，执行添加操作
    selectedFilmsValue.value.push({id: row.id, filmName: row.filmName});
  }
};
const saveFilmParam = ref({
  subjectId: subjectId,
})
const saveFilm = () => {
  saveFilmParam.value.filmId = selectedFilmsValue.value.map(film => film.id).join(',');
  let data = qs.stringify(saveFilmParam.value);
  axios.post(BASE_URL + '/v1/filmSubject/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          selectedFilmsValue.value = [];
          addFilmVisible.value = false;
          select();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}

const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    selectedFilmsValue.value = [];
    addFilmVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}
const deleteFilmSubject = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/filmSubject/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            select();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}
</script>


<style scoped>
.checkbox-item {
  display: block;
  margin: 10px 0;
}

/* 定义进入和离开的动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s ease, transform .5s ease;
}

.fade-enter-from, .fade-leave-to /* .fade-leave-active in <2.1.8 */
{
  opacity: 0;
  transform: scale(0);
}

.fade-enter-to, .fade-leave-from {
  opacity: 1;
  transform: scale(1);
}
</style>